import React, { useState } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { logins } from '@/store/actions/login'
import { useLocation, useHistory } from 'react-router-dom'

export default function Login() {
  const [loading, setLoding] = useState(false)
  const history = useHistory()
  const location = useLocation()
  // console.log(props)

  const dispatch = useDispatch()
  const finish = async (values) => {
    // console.log('Success:', values)
    // 发送请求，进行登录
    setLoding(true)
    try {
      await dispatch(logins(values))
      message.success('登录成功', 1, () => {
        const from = location.state ? location.state.from : '/home'
        history.replace(from)
        // history.push('/home')
      })
    } catch (e) {
      message.error(e.response.data.message, 1, () => {
        setLoding(false)
      })
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img src={logo} alt="" className="login-logo" />
        <Form
          autoComplete="off"
          size="large"
          validateTrigger={['onBlur', 'onChange']}
          initialValues={{ mobile: '13911111111', code: '246810', agree: true }}
          onFinish={finish}
        >
          <Form.Item
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
              },
              { required: true, message: '请输入手机号' },
            ]}
          >
            <Input placeholder="请输入手机号"></Input>
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码验证不通过' },
            ]}
          >
            <Input placeholder="请输入验证码"></Input>
          </Form.Item>
          <Form.Item
            valuePropName="checked"
            name="agree"
            rules={[
              {
                validator: (rule, value) => {
                  if (value === true) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('请阅读并同意协议和条款'))
                  }
                },
              },
            ]}
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
